import { Message } from 'element-ui'
// 机器人问答相关接口
export const fetchURl = {
  screenStreamChat: '/chat-messages', // 主对话
  conversations: '/conversations', // 历史会话列表
  messages: '/messages' // 当前会话的消息列表
}
/**
 * @description: 封装fetch
 * @param api
 * @param {any} data
 * @param {AbortSignal} signal
 * @return {Promise}
 */
export const baseURL = 'http://151.100.35.71/v1'
//export const baseURL = 'http://117.50.181.115/v1'
//export const token = 'Bearer app-htU3CHJklYSd6WcUuA5N9NPX'
//export const token = 'Bearer app-iBtcMg1bh4ucNkW9Q9UtGLkp'
//export const token = 'Bearer app-SRbeYGM2HSpienc5Fl6LDoPJ'
export const token = 'Bearer app-GBqkIYjZxExyOPAfZJqzZl8S'

export const postFetch = (api = '', data, signal) => {
  return new Promise((resolve, reject) => {
    fetch(baseURL + api, {
      signal,
      method: 'POST',
      // baseURL: process.env.VUE_APP_ROBOT_URL,
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        Authorization: token
      },
      body: JSON.stringify(data)
    })
      .then(async (response) => {
        const resContentType = response.headers.get('content-type')
        if (resContentType.includes('application/json')) {
          const cloneData = response.clone()
          try {
            const info = await cloneData.json()
            if (info?.code && info?.code !== '0000') {
              if (['UC/TOKEN_NOT_FOUND', 'UC/AUTH_TOKEN_EXPIRED', 'UC/CREATE_TOKEN_ERROR'].includes(info.code)) {
                Message.error(`${info?.message || '账号已在其他地方登录或登录信息过期!'}`)
                return false
              } else {
                Message.error(`${info?.message || '网络开小差了, 请稍后重试!'}`)
              }
            } else {
              if (response.ok) {
                resolve(info)
              } else {
                reject(new Error(`HTTP Error ${response.status}: ${response.statusText}`))
              }
            }
          } catch (error) {
            console.log('fetch error', error)
          }
        } else { // 数据流数据原样返回
          return resolve(response)
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}
